import Vue from 'vue'

let mockFiles = require.context('./module', true, /\.js$/)
let mock = {}
let mockFun = {}

mockFiles.keys().reduce((module, modulePath) => {
	let moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
	moduleName = moduleName.replace('-', '_')
	let fileName = modulePath.replace(/^\.\/(.*)$/, '$1')
	let data = require('@/assets/mock/module/' + fileName).default
	
	let level = moduleName.split('/')
	if (level.length === 1) {
		filterFun(mock, level[0], data)
		getFun(mockFun, level[0], data)
		return module
	}
	
	let obj = {}
	let fun = {}
	for (let i = level.length - 1; i >= 0; i--) {
		if (i === 0) {
			if (mock[level[i]]) {
				filterFun(mock, level[i], Object.assign(mock[level[i]], obj), true)
				getFun(mockFun, level[i], Object.assign(mock[level[i]], fun), true)
			} else {
				filterFun(mock, level[i], obj, true)
				getFun(mockFun, level[i], fun, true)
			}
		} else if (i === level.length - 1) {
			filterFun(obj, level[i], data)
			getFun(fun, level[i], data)
		} else {
			let _obj = {}
			let _fun = {}
			
			let temporary_obj = obj
			let temporary_fun = fun
			
			obj = _obj
			obj = _fun
			
			_obj = temporary_obj
			_fun = temporary_fun
			
			filterFun(obj, level[i], _obj)
			getFun(fun, level[i], _fun)
		}
	}
	
	return module
}, {})

Vue.prototype.$mock = mock


if (process.env.VUE_APP_MOCK) {
	// 动态生成mock接口
	let MockAdapter = require('axios-mock-adapter')
	let mockAdapter = new MockAdapter(Vue.prototype.$http)
	
	for (let item in mockFun) {
		if (!item instanceof Function) {
			continue
		}
		
		let data = mockFun[item]()
		switch(data.method) {
			case 'get':
				mockAdapter.onGet(data.path).reply(data.state, data)
				break;
			case 'post':
				mockAdapter.onPost(data.path).reply(data.state, data)
				break;
			case 'put':
				mockAdapter.onPut(data.path).reply(data.state, data)
				break;
			case 'delete':
				mockAdapter.onDelete(data.path).reply(data.state, data)
				break;
			case 'patch':
				mockAdapter.onPatch(data.path).reply(data.state, data)
				break;
		}
	}
	
}


function filterFun(mock = {}, key, value, level = false) {
	let obj = {}
	let arr = []
	if (value instanceof Array) {
		arr = value
	} else if (value instanceof Object && level) {
		obj = value
	} else {
		for (let key in value) {
			if (!value.hasOwnProperty(key)) {
				continue
			}
			if (value[key] instanceof Function) {
				continue
			}
			if (value[key] instanceof Object) {
				arr.push(value[key])
			} else {
				Vue.set(obj, key, value[key])
			}
		}
	}

	if (arr.length != 0) {
		Vue.set(mock, key, arr)
	} else if (JSON.stringify(obj) != '{}') {
		Vue.set(mock, key, obj)
	}
}
function getFun(mock = {}, key, value, level = false) {
	if (value instanceof Object) {
		for (let item in value) {
			if (!value.hasOwnProperty(item)) {
				continue
			}
			if (value[item] instanceof Function) {
				Vue.set(mock, key + '_' + item, value[item])
			}
		}
	} else if (value instanceof Function) {
		Vue.set(mock, key, value)
	}
}